<?php

namespace app\api\model;

use think\db\Query;
use think\Model;

/**
 * Device
 */
class Device extends Model
{
    const HEARTBEAT_EXPIRE = 3600;
    // 表名
    protected $name = 'device';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    protected $updateTime = false;


    public function app(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(App::class, 'appid', 'appid');
    }


    public function getOnlineStatusAttr( ){
        
        if(!empty($this->heartbeat_time)){
            $heartbeatTime = strtotime($this->heartbeat_time);
            $now = time();
            if($now - $heartbeatTime > self::HEARTBEAT_EXPIRE){
                // 超出心跳时间
                return  false;
            }
        }
        return true;
    }

    public static function whereOnline(Query|null $query = null){
        if($query == null){
            $query = self::query();
        }
        $now = time();
        $validTime = date('Y-m-d H:i:s', $now - self::HEARTBEAT_EXPIRE);
        return $query->where('heartbeat_time', '>=', $validTime);
    }


}